<?php
if (!defined('__COLA_DIR__')) exit;

/**
 * 评论基类
 *
 * @author edikud
 * @package Widget
 * @copyright Copyright (c) 2019 Cola (http://www.mcooo.com)
 * @license GNU General Public License 2.0
 */
class Widget_Abstract_Comments extends Widget
{
    /**
     * 获取当前内容结构
     *
     * @access protected
     * @return array
     */
    protected function ___parentContent()
    {
		return $this->widget('Widget_Contents_List@'.$this->cid, 
		    array('cid'=>$this->cid))->row;
    }

    /**
     * 获取当前评论标题
     *
     * @access protected
     * @return string
     */
    protected function ___title()
    {
        return $this->parentContent['title'];
    }

    /**
     * 获取当前评论链接
     *
     * @access protected
     * @return string
     */
    protected function ___permalink()
    {
        if ($this->options->commentsPageBreak) {
            
            $coid = $this->coid;

            $comments = $this->db->select('coid', 'parent')
			    ->from('table.comments')
                ->where('cid = ?', $this->parentContent['cid'])
                ->where('coid ' . ('DESC' == $this->options->commentsOrder ? '>=' : '<=') . ' ?', $coid)
                ->order('coid', 'ASC')
			    ->fetchAll();

            $commentsMap = array();
            $total = 0;
            
            foreach ($comments as $comment) 
			{
                $commentsMap[$comment['coid']] = $comment['parent'];
                
                if (0 == $comment['parent'] || !isset($commentsMap[$comment['parent']])) {
                    $total ++;
                }
            }

            $currentPage = ceil($total / $this->options->commentsPageSize);
            
            $pageRow = array('permalink' => $this->parentContent['pathinfo'], 'commentPage' => $currentPage);
            return Router::url('comment_page',
                $pageRow, $this->options->index) . '#' . $this->theId;
        }
        
        return $this->parentContent['permalink'] . '#' . $this->theId;
    }

    /**
     * 获取当前评论内容
     *
     * @access protected
     * @return string
     */
    protected function ___content()
    {
		$content = $this->text;
		
		/** 插件接口 */
		//HOOK $content | PLUG_Abstract_Comments_Text($content, $this);

		return $content;
    }

    /**
     * 输出词义化日期
     *
     * @access protected
     * @return string
     */
    protected function ___dateWord()
    {
        return $this->date->word();
    }

    /**
     * 锚点id
     *
     * @access protected
     * @return string
     */
    protected function ___theId()
    {
        return 'comment-' . $this->coid;
    }

    /**
     * 获取查询对象
     *
     * @access public
     * @return Db_Query
     */
    public function select()
    {
        return $this->db->select()
		    ->from('table.comments');
    }

    /**
     * 增加评论
     *
     * @access public
     * @param array $values 评论结构数组
     * @return integer
     */
    public function insert(array $values)
    {
        /** 构建插入结构 */
        $comment = array(
            'cid'           =>  empty($values['cid']) ? 0 : intval($values['cid']),
			'uid'           =>  isset($values['uid']) ? intval($values['uid']) : $this->user->uid,
            'parent'        =>  empty($values['parent']) ? 0 : intval($values['parent']),
            'ownerId'       =>  empty($values['ownerId']) ? 0 : intval($values['ownerId']),
            'created'       =>  empty($values['created']) ? $this->options->time : $values['created'],
            'ip'            =>  empty($values['ip']) ? $this->request->longIp() : $values['ip'],
            'text'          =>  empty($values['text']) ? '' : $this->filterText($values['text']),
        );

        if (!empty($values['coid'])) {
            $comment['coid'] = $values['coid'];
        }
		
		/** 插件接口 */
		//HOOK $comment | PLUG_Abstract_Comments_Insert($values, $this);		

        return $this->db->insert('table.comments')
		    ->values($comment)
			->lastInsertId();
    }

    /**
     * 更新评论
     *
     * @access public
     * @param int $coid 评论coid
     * @param array $values 评论结构数组
     * @return integer
     */
    public function update($coid, array $values)
    {
        /** 构建插入结构 */
        $update = array(
            'cid'           =>  empty($values['cid']) ? 0 : intval($values['cid']),
			'uid'           =>  isset($values['uid']) ? intval($values['uid']) : $this->user->uid,
            'parent'        =>  empty($values['parent']) ? 0 : intval($values['parent']),
            'ownerId'       =>  empty($values['ownerId']) ? 0 : intval($values['ownerId']),
            'ip'            =>  empty($values['ip']) ? $this->request->longIp() : $values['ip'],
            'text'          =>  empty($values['text']) ? '' : $this->filterText($values['text']),
        );

        $comment = array();
        foreach ($values as $key => $val) {
            if (array_key_exists($key, $update)) {
                $comment[$key] = $update[$key];
            }
        }

        /** 更新创建时间 */
        if (!empty($values['created'])) {
            $comment['created'] = $values['created'];
        }
		
		/** 插件接口 */
		//HOOK $comment | PLUG_Abstract_Comments_Update($values, $this);
		
        return $this->db->update('table.comments')
		    ->where('coid = ?', $coid)
			->values($comment)
			->affectedRows();
    }

    /**
     * 删除数据
     *
     * @access public
     * @param int $coid 评论coid
     * @return integer
     */
    public function delete($coid)
    {
		/** 插件接口 */
		//HOOK PLUG_Abstract_Comments_Delete($coid, $this);
		
        return $this->db->delete('table.comments')
		    ->where('coid = ?', $coid)
			->affectedRows();
    }

    /**
     * filterText 
     * 
     * @param mixed $html 
     * @access public
     * @return string
     */
    public function filterText($html)
    {
		/** 插件接口 */
		//HOOK {$plugged} $html | PLUG_Abstract_Comments_Filter_Text($html, $this);
		
        if (!$plugged ) {
			$html = strip_tags($html, '<p><br>' . $this->options->commentsHTMLTagAllowed);
        }
        return $html;
    }
	
    /**
     * 通用过滤器
     *
     * @access public
     * @param array $value 需要过滤的行数据
     * @return array
     */
    public function filter(array $value)
    {
        isset($value['created']) && $value['date'] = new Date($value['created']);
		
		/** 插件接口 */
		//HOOK $value | PLUG_Abstract_Comments_Filter($value, $this);
		
        return $value;
    }

    /**
     * 将每行的值压入堆栈
     *
     * @access public
     * @param array $value 每行的值
     * @return array
     */
    public function push(array $value)
    {
        $value = $this->filter($value);
        return parent::push($value);
    }

    /**
     * 评论是否可以被修改
     *
     * @access public
     * @return boolean
     */
    public function isWriteable()
    {
        if ($this->have() && ($this->user->pass('editor', true) || $this->ownerId == $this->user->uid)) {
            return true;
        }
        return false;
    }
	
    /**
     * 输出文章发布日期
     *
     * @access public
     * @param string $format 日期格式
     * @return void
     */
    public function date($format = NULL)
    {
        echo $this->date->format(empty($format) ? $this->options->commentDateFormat : $format);
    }

    /**
     * 调用用户
     *
     * @access public
     * @return void
     */
    protected function ___author()
    {
        return $this->widget('Widget_Users_List@' . $this->uid, 
		    array('uid' => $this->uid, 'limit' => 1));
    }

    /**
     * 输出评论摘要
     *
     * @access public
     * @param integer $length 摘要截取长度
     * @param string $trim 摘要后缀
     * @return void
     */
    public function excerpt($length = 100, $trim = '...')
    {
        echo Common::subStr(strip_tags($this->text), 0, $length, $trim);
    }
}

